<template>
	<div class="academic-achievement-review">
		<div class="page-header">
			<h1 class="page-title">学术成果审核</h1>
			<div class="header-actions">
				<el-button type="success" @click="exportData">
					<el-icon><Download /></el-icon>
					导出数据
				</el-button>
				<el-button type="primary" @click="fetchAchievements">刷新</el-button>
			</div>
		</div>

		<el-card>
			<div class="filter-bar">
				<el-select v-model="filterStatus" placeholder="审核状态" style="width: 140px;" clearable @change="handleFilterChange">
					<el-option label="全部" value="" />
					<el-option label="待审核" value="PENDING" />
					<el-option label="已通过" value="APPROVED" />
					<el-option label="已驳回" value="REJECTED" />
				</el-select>
				
				<el-select v-model="filterType" placeholder="论文类型" style="width: 120px;" clearable @change="handleFilterChange">
					<el-option label="全部" value="" />
					<el-option label="期刊论文" value="期刊论文" />
					<el-option label="会议论文" value="会议论文" />
					<el-option label="书评" value="书评" />
					<el-option label="报刊理论文章" value="报刊理论文章" />
				</el-select>
				
				<el-select v-model="filterLanguage" placeholder="发表语言" style="width: 100px;" clearable @change="handleFilterChange">
					<el-option label="全部" value="" />
					<el-option label="中文" value="中文" />
					<el-option label="英文" value="英文" />
				</el-select>
				
				<el-date-picker v-model="filterYear" type="year" placeholder="发表年份" value-format="YYYY" style="width: 120px;" @change="handleFilterChange" />
				
				<div class="filter-summary">
					<el-tag type="info" size="small">
						共 {{ filteredAchievements.length }} 个学术成果
					</el-tag>
					<el-button size="small" style="margin-left: 8px;" @click="clearFilters">清除筛选</el-button>
				</div>
			</div>

			<el-table :data="filteredAchievements" stripe v-loading="loading">
				<el-table-column label="第一作者" width="120" show-overflow-tooltip>
					<template #default="{ row }">
						<div v-if="row.authors && row.authors.length > 0">
							<div v-for="author in row.authors" :key="author.id">
								<span v-if="author.authorOrder === '第一作者'" class="first-author">
									{{ author.authorName }}
								</span>
							</div>
						</div>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="title" label="论文标题" min-width="300" show-overflow-tooltip />
				<el-table-column prop="type" label="论文类型" width="120">
					<template #default="{ row }">
						<el-tag :type="getTypeTagType(row.type)" size="small">
							{{ row.type }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="language" label="发表语言" width="80" />
				<el-table-column prop="journalConference" label="期刊/会议名称" min-width="200" show-overflow-tooltip />
				<el-table-column prop="publicationYear" label="发表年份" width="100" />
				<el-table-column prop="journalLevel" label="期刊级别/分区" width="120" show-overflow-tooltip />
				<el-table-column prop="status" label="审核状态" width="100">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createdAt" label="提交时间" width="160">
					<template #default="{ row }">
						{{ formatDateTime(row.createdAt) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150" fixed="right">
					<template #default="{ row }">
						<el-button type="primary" size="small" @click="viewAchievement(row)">查看</el-button>
						<el-button v-if="row.status === 'PENDING'" type="success" size="small" @click="openReview(row)">审核</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 查看对话框 -->
		<el-dialog v-model="showViewDialog" title="学术成果详情" width="800px">
			<el-descriptions :column="2" border>
				<el-descriptions-item label="论文标题">{{ viewData.title }}</el-descriptions-item>
				<el-descriptions-item label="论文类型">{{ viewData.type }}</el-descriptions-item>
				<el-descriptions-item label="发表语言">{{ viewData.language }}</el-descriptions-item>
				<el-descriptions-item label="发表年份">{{ viewData.publicationYear }}</el-descriptions-item>
				<el-descriptions-item label="发表月份">{{ viewData.publicationMonth }}</el-descriptions-item>
				<el-descriptions-item label="DOI号">{{ viewData.doi || '-' }}</el-descriptions-item>
				<el-descriptions-item label="期刊级别/分区">{{ viewData.journalLevel || '-' }}</el-descriptions-item>
				<el-descriptions-item label="会议级别">{{ viewData.conferenceLevel || '-' }}</el-descriptions-item>
				<el-descriptions-item label="学科领域/关键词" :span="2">{{ viewData.keywords || '-' }}</el-descriptions-item>
				<el-descriptions-item label="发表期刊/会议名称" :span="2">{{ viewData.journalConference || '-' }}</el-descriptions-item>
				<el-descriptions-item label="审核状态">
					<el-tag :type="getStatusType(viewData.status)">{{ getStatusText(viewData.status) }}</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="提交时间">{{ formatDateTime(viewData.createdAt) }}</el-descriptions-item>
				<el-descriptions-item v-if="viewData.reviewOpinion" label="审核意见" :span="2">{{ viewData.reviewOpinion }}</el-descriptions-item>
			</el-descriptions>

			<!-- 作者信息 -->
			<div v-if="viewData.authors && viewData.authors.length > 0" style="margin-top: 20px;">
				<h4>作者信息</h4>
				<el-table :data="viewData.authors" border>
					<el-table-column prop="authorName" label="作者姓名" />
					<el-table-column prop="authorUnit" label="作者单位" />
					<el-table-column prop="authorOrder" label="署名顺序" />
					<el-table-column prop="isCurrentUnit" label="是否本单位">
						<template #default="{ row }">
							<el-tag :type="row.isCurrentUnit ? 'success' : 'info'">
								{{ row.isCurrentUnit ? '是' : '否' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="staffNo" label="工号" />
				</el-table>
			</div>

			<!-- 附件信息 -->
			<div v-if="viewData.attachments && viewData.attachments.length > 0" style="margin-top: 20px;">
				<h4>证明材料</h4>
				<el-table :data="viewData.attachments" border>
					<el-table-column prop="fileName" label="文件名" />
					<el-table-column prop="fileType" label="文件类型" />
					<el-table-column prop="fileSize" label="文件大小">
						<template #default="{ row }">
							{{ formatFileSize(row.fileSize) }}
						</template>
					</el-table-column>
					<el-table-column label="操作">
						<template #default="{ row }">
							<el-button type="primary" size="small" @click="downloadFile(row)">下载</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>

		<!-- 审核对话框 -->
		<el-dialog v-model="showReviewDialog" title="学术成果审核" width="600px">
			<div class="review-info">
				<el-descriptions :column="1" border>
					<el-descriptions-item label="论文标题">{{ reviewAchievement?.title }}</el-descriptions-item>
					<el-descriptions-item label="论文类型">{{ reviewAchievement?.type }}</el-descriptions-item>
					<el-descriptions-item label="发表语言">{{ reviewAchievement?.language }}</el-descriptions-item>
					<el-descriptions-item label="当前状态">{{ getStatusText(reviewAchievement?.status) }}</el-descriptions-item>
				</el-descriptions>
			</div>
			
			<el-form :model="reviewForm" label-width="100px" style="margin-top: 20px;">
				<el-form-item label="审核结果" required>
					<el-radio-group v-model="reviewForm.status">
						<el-radio label="APPROVED">通过</el-radio>
						<el-radio label="REJECTED">驳回</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="审核意见" required>
					<el-input v-model="reviewForm.opinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
				</el-form-item>
			</el-form>
			
			<template #footer>
				<el-button @click="showReviewDialog = false">取消</el-button>
				<el-button type="primary" :loading="reviewLoading" @click="submitReview">提交审核</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { getAllAcademicAchievements, reviewAcademicAchievement, getAcademicAchievement } from '@/api/academicAchievement'

// 响应式数据
const loading = ref(false)
const achievements = ref([])
const viewData = ref({})
const showViewDialog = ref(false)
const showReviewDialog = ref(false)
const reviewAchievement = ref(null)
const reviewLoading = ref(false)

// 筛选条件
const filterStatus = ref('')
const filterType = ref('')
const filterLanguage = ref('')
const filterYear = ref('')

// 审核表单
const reviewForm = reactive({
	status: '',
	opinion: ''
})

// 计算属性
const filteredAchievements = computed(() => {
	let result = achievements.value

	if (filterStatus.value) {
		result = result.filter(item => item.status === filterStatus.value)
	}

	if (filterType.value) {
		result = result.filter(item => item.type === filterType.value)
	}

	if (filterLanguage.value) {
		result = result.filter(item => item.language === filterLanguage.value)
	}

	if (filterYear.value) {
		result = result.filter(item => item.publicationYear === parseInt(filterYear.value))
	}

	return result
})

// 方法
const fetchAchievements = async () => {
	try {
		loading.value = true
		const response = await getAllAcademicAchievements()
		achievements.value = Array.isArray(response) ? response : (response?.data || [])
	} catch (error) {
		console.error('获取学术成果列表失败:', error)
		ElMessage.error('获取学术成果列表失败')
	} finally {
		loading.value = false
	}
}

const viewAchievement = async (row) => {
	try {
		const response = await getAcademicAchievement(row.id)
		viewData.value = response.achievement || response
		showViewDialog.value = true
	} catch (error) {
		console.error('获取详情失败:', error)
		ElMessage.error('获取详情失败')
	}
}

const openReview = (row) => {
	reviewAchievement.value = row
	reviewForm.status = ''
	reviewForm.opinion = ''
	showReviewDialog.value = true
}

const submitReview = async () => {
	try {
		if (!reviewForm.status || !reviewForm.opinion) {
			ElMessage.warning('请填写完整的审核信息')
			return
		}
		
		reviewLoading.value = true
		
		await reviewAcademicAchievement(reviewAchievement.value.id, {
			status: reviewForm.status,
			opinion: reviewForm.opinion
		})
		
		ElMessage.success('审核完成')
		showReviewDialog.value = false
		fetchAchievements()
	} catch (error) {
		console.error('审核失败:', error)
		ElMessage.error('审核失败')
	} finally {
		reviewLoading.value = false
	}
}

const handleFilterChange = () => {
	// 实时筛选，无需额外处理
}

const clearFilters = () => {
	filterStatus.value = ''
	filterType.value = ''
	filterLanguage.value = ''
	filterYear.value = ''
}

const getTypeTagType = (type) => {
	const types = {
		'期刊论文': 'primary',
		'会议论文': 'success',
		'书评': 'warning',
		'报刊理论文章': 'info'
	}
	return types[type] || 'info'
}

const getStatusType = (status) => {
	const types = {
		'PENDING': 'info',
		'APPROVED': 'success',
		'REJECTED': 'danger'
	}
	return types[status] || 'info'
}

const getStatusText = (status) => {
	const texts = {
		'PENDING': '待审核',
		'APPROVED': '已通过',
		'REJECTED': '已驳回'
	}
	return texts[status] || status
}

const formatDateTime = (date) => {
	if (!date) return '-'
	try {
		return new Date(date).toLocaleString('zh-CN')
	} catch {
		return '-'
	}
}

const formatFileSize = (size) => {
	if (!size) return '-'
	if (size < 1024) return size + ' B'
	if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
	return (size / (1024 * 1024)).toFixed(2) + ' MB'
}

const downloadFile = (file) => {
	// 实现文件下载逻辑
	ElMessage.info('文件下载功能待实现')
}

// 生命周期
// 导出数据
const exportData = async () => {
	const { exportAdminData } = await import('@/utils/exportUtils')
	
	const filters = {
		search: searchKeyword.value,
		type: filterType.value,
		status: filterStatus.value
	}
	
	await exportAdminData('academic-achievements', filters, '学术成果审核列表.xlsx')
}

onMounted(() => {
	fetchAchievements()
})
</script>

<style scoped>
.academic-achievement-review {
	max-width: 1400px;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
}

.page-title {
	margin: 0;
	color: #333;
	font-size: 24px;
	font-weight: 500;
}

.header-actions {
	display: flex;
	align-items: center;
}

.filter-bar {
	margin-bottom: 16px;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	gap: 16px;
}

.filter-summary {
	margin-left: auto;
}

.review-info {
	margin-bottom: 20px;
}

.first-author {
	color: #e6a23c;
	font-weight: bold;
}
</style>
